<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="保存"
    cancelText="关闭"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <p class="g-font-14n1 g-mb20" v-if="addType">父节点：{{ parentNodeName }}</p>
    <el-form ref="formRef" :model="formState" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="物料名称" prop="nodeName">
            <el-input v-model="formState.nodeName" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料编码" prop="nodeCode">
            <el-input v-model="formState.nodeCode" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料类别" prop="dataType">
            <el-radio-group v-model="formState.dataType">
              <el-radio :label="item.value" v-for="item in NodeTypeOptions" :key="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="材料类别或牌号" v-if="formState.dataType == 'ITEM'">
            <el-input
              v-model="formState.materialCategory"
              type="text"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
          <el-form-item label="材料类别或牌号" prop="materialCategory" v-else>
            <el-input
              v-model="formState.materialCategory"
              type="text"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity">
            <el-input v-model="formState.quantity" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单位用量" prop="dosage">
            <CDosageAndUnit
              v-model:dosage="formState.dosage"
              v-model:unit="formState.unit"
              :digit="9"
              is-group
              dealPcs
            ></CDosageAndUnit>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="单位重量" prop="weight" v-if="!isWeightUnitComputed">
            <CDosageAndUnit
              v-model:dosage="formState.weight"
              v-model:unit="formState.weightUnit"
              :can-negative="false"
              unitType="WEIGHT"
            ></CDosageAndUnit>
          </el-form-item>
        </el-col> -->
        <el-col :span="12" v-if="formState.dataType !== 'ITEM'">
          <el-form-item label="材料使用系数" prop="useRate">
            <el-input
              class="material-input-has-append"
              v-model="formState.useRate"
              type="number"
              v-positive-only:2
              placeholder="请输入"
              clearable
              @wheel.stop.prevent
            >
              <template #suffix>
                <span>%</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formState.dataType !== 'ITEM'">
          <el-form-item label="偏差范围" prop="deviationRange">
            <el-input
              class="material-input-has-append"
              v-model="formState.deviationRange"
              type="number"
              v-positive-only:2
              placeholder="请输入"
              clearable
              @wheel.stop.prevent
            >
              <template #suffix>
                <span>%</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formState.dataType !== 'ITEM'">
          <el-form-item label="材料循环比例" prop="recycleRate">
            <el-input
              class="material-input-has-append"
              v-model="formState.recycleRate"
              type="number"
              v-positive-only:2
              placeholder="请输入"
              clearable
              @wheel.stop.prevent
            >
              <template #suffix>
                <span>%</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="供应商" prop="supplierNo">
            <CSelect
              v-model="formState.supplierNo"
              placeholder="请选择"
              clearable
              filterable
              @change="changeSupplier"
            >
              <el-option
                v-for="item in supplierList"
                :key="item.supplierNo"
                :label="item.supplierName"
                :value="item.supplierNo"
              />
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="formState.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup name="MaterialDialog">
import {
  withDefaults,
  defineProps,
  defineEmits,
  computed,
  watch,
  reactive,
  ref,
  inject
} from 'vue';
import { CDialog } from '@/components/CDialog';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import {
  postCheckUnitBeforeEditSubmit,
  editNode,
  createNode,
  getNodeDetail
} from '@/apis/pcf/myModel/modelDetail';
import type { GetListBomTreeResult } from '@/apis/pcf/myModel/model/modelDetailModel';
import { useMessage } from '@/hooks/useMessage';
import { NodeTypeOptions, NodeTypeEnum } from '@/constants/enum';
import { MaterialDialogOperationType } from './material-dialog';
import { rules } from './rules';
import { rateToNumber, numberToRate } from '@/utils';
import { useWeightAndUnit } from '@/hooks/useWeightAndUnit';
import { getSupplierOptions } from '@/apis/pcf/supplier/supplierList';
import { CSelect } from '@/components/CSelect';
import { getSupplierNoWithNoMsg } from '@/apis/pcf/supplier/supplierList';
import { MODEL_DETAIL_ROOT, ModelDetailRootProvider } from '@/views/pcf/myModel/modelDetail/types';

interface MaterialDialogProps {
  visible: boolean;
  nodeNo?: string;
  modelNo?: string;
  nodeItem?: GetListBomTreeResult;
  enterpriseNo?: string;
  addType?: 'peer' | 'child';
}
const props = withDefaults(defineProps<MaterialDialogProps>(), {});
const emits = defineEmits([
  'update:visible',
  'refresh',
  'strong-refresh',
  'expand-refresh',
  'load-bom-count',
  'refresh-and-clear'
]);
const { modelDetail } = inject(MODEL_DETAIL_ROOT) as ModelDetailRootProvider;

const { createMessage, createConfirm } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
    } else {
      formRef.value?.resetFields();
    }
  }
);

const formRef = ref();
const loading = ref(false);
const supplierList = ref<any[]>([]);
/**
 * 表单内容
 */
const formState = reactive({
  quantity: null as unknown as number,
  nodeNo: '',
  nodeName: '',
  nodeCode: '',
  dataType: 'ITEM' as keyof typeof NodeTypeEnum,
  materialCategory: '',
  dosage: null as any,
  unit: 'pcs',
  weight: '',
  weightUnit: 'kg',
  useRate: null as unknown as number,
  deviationRange: null as unknown as number,
  recycleRate: null as unknown as number,
  supplierNo: '',
  supplierName: '',
  supplierCode: '',
  remark: ''
});

watch(
  () => formState.unit,
  val => {
    setTimeout(() => {
      formRef.value?.clearValidate('dosage');
    }, 0);
  }
);

const originalSupplierName = ref('');
const { isWeightUnitComputed } = useWeightAndUnit({
  props: formState
});

/**
 * 操作类型
 */
const operationType = ref<MaterialDialogOperationType>();

/**
 * 弹窗标题
 */
const title = computed(() => {
  let title = '';
  if (operationType.value === 'ADD') {
    if (props.addType === 'peer') {
      title = '新增同级物料';
    } else if (props.addType === 'child') {
      title = '新增子级物料';
    } else {
      title = '新增物料信息';
    }
  } else {
    title = '编辑物料信息';
  }
  // return operationType.value === 'ADD' ? '新增物料信息' : '编辑物料信息';
  return title;
});

const loadSupplierList = async () => {
  const data = await getSupplierOptions(modelDetail.value?.enterpriseNo || '');
  console.log('loadSupplierList data', data);
  supplierList.value = data ?? [];
};
const changeSupplier = (selectVal: string) => {
  if (selectVal) {
    const index = supplierList.value.findIndex((n: any) => n.supplierNo === selectVal);
    if (index > -1) {
      formState.supplierName = supplierList.value[index].supplierName;
      formState.supplierCode = supplierList.value[index].supplierCode;
    }
  } else {
    formState.supplierName = '';
    formState.supplierCode = '';
  }
};

const parentNodeName = ref('');
/**
 * 初始化
 */
function init() {
  originalSupplierName.value = '';
  loadSupplierList();
  loading.value = false;
  if (!props.nodeNo) {
    operationType.value = 'ADD';
    formState.unit = 'kg';
    formState.materialCategory = '';
    formState.remark = '';
    formState.supplierName = '';
    formState.supplierCode = '';
    if (props.addType === 'peer') {
      // 同级调接口获取父节点名称
      getParentNodeInfo(props.nodeItem?.parentNodeNo || '');
    } else {
      // 子级直接取当前节点的名称
      parentNodeName.value = props.nodeItem?.nodeName || '-';
    }
  } else {
    operationType.value = 'EDIT';
    getData(props.nodeNo);
  }
}

/**
 * 获取父节点名称
 * @param nodeNo string
 */
const getParentNodeInfo = async (nodeNo: string) => {
  if (nodeNo) {
    if (nodeNo === '-1') {
      parentNodeName.value = '根节点';
    } else {
      const res = await getNodeDetail(nodeNo);
      parentNodeName.value = res.nodeName || '-';
    }
  } else {
    parentNodeName.value = '-';
  }
};

/**
 * 检查供应商编号是否存在
 * @param row
 */
const checkSupplier = (supplierName: string) => {
  return new Promise((resolve, reject) => {
    getSupplierNoWithNoMsg(
      supplierName,
      props.enterpriseNo as string,
      formState.supplierCode || undefined
    )
      .then(res => {
        if (res.supplierNo) {
          resolve(res.supplierNo);
        } else {
          reject('');
        }
      })
      .catch(() => {
        reject('');
      });
  });
};
/**
 * 获取节点详情
 */
async function getData(nodeNo: string) {
  try {
    loading.value = true;
    const res = await getNodeDetail(nodeNo);
    formState.nodeNo = res.nodeNo;
    formState.quantity = res.quantity;
    formState.nodeName = res.nodeName;
    formState.nodeCode = res.nodeCode;
    formState.dataType = res.dataType;
    formState.materialCategory = res.materialCategory;
    res.unit && (formState.unit = res.unit);
    if (res.unit == 'pcs') {
      formState.dosage = '-';
    } else {
      formState.dosage = res.dosage;
    }
    formState.weight = res.weight || '';
    res.weightUnit && (formState.weightUnit = res.weightUnit);
    formState.useRate = rateToNumber(res.useRate);
    formState.deviationRange = rateToNumber(res.deviationRange);
    formState.recycleRate = rateToNumber(res.recycleRate);
    formState.supplierName = res.supplierName;
    originalSupplierName.value = res.supplierName;
    formState.supplierNo = res.supplierNo || formState.supplierName;
    formState.supplierCode = res.supplierCode;
    formState.remark = res.remark;
    //supplierName 存在&& supplierNo不存在才去调用接口查询supplierNo
    if (res.supplierName && !res.supplierNo) {
      checkSupplier(res.supplierName)
        .then(supplierNo => {
          formState.supplierNo = supplierNo as string;
          loading.value = false;
        })
        .catch(() => {
          // TODO:显示供应商不存在，请前往供应商管理添加
          loading.value = false;
        });
    } else {
      loading.value = false;
    }
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}

/**
 * 保存按钮
 */
function handleConfirm() {
  console.log('handleConfirm');
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitFlowReq();
    }
  });
}

/**
 * 接口请求
 */
async function submitFlowReq() {
  console.log('submitFlowReq');
  if (operationType.value === 'ADD') {
    handleEditNodeReq();
  } else {
    try {
      loading.value = true;
      const checkRes = await postCheckUnitBeforeEditSubmit(props.nodeNo as string, formState.unit);
      if (!checkRes) {
        createConfirm('修改不一致的用量单位', '已关联的因子需要重新选择，是否继续', {
          iconType: 'warning',
          confirmButtonText: '继续提交',
          cancelButtonText: '取消修改'
        })
          .then(() => {
            handleEditNodeReq();
          })
          .catch(() => {
            loading.value = false;
          });
        return;
      }
      handleEditNodeReq();
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  }
}

/**
 * 实际修改请求提交
 */
async function handleEditNodeReq() {
  try {
    loading.value = true;
    const params = {
      ...formState,
      useRate: numberToRate(formState.useRate),
      deviationRange: numberToRate(formState.deviationRange),
      recycleRate: numberToRate(formState.recycleRate),
      dosage: formState.dosage == '-' ? null : formState.dosage,
      supplierNo: formState.supplierNo == formState.supplierName ? '' : formState.supplierNo,
      supplierCode: formState.supplierCode
    };
    if (operationType.value === 'ADD') {
      // 新增接口
      if (props.addType === 'peer') {
        // 同级
        Object.assign(params, {
          parentNodeNo: props.nodeItem?.parentNodeNo,
          nodeNo: props.nodeItem?.nodeNo,
          modelNo: props.modelNo
        });
        await createNode(params);
      } else {
        // 子级
        Object.assign(params, {
          parentNodeNo: props.nodeItem?.nodeNo,
          nodeNo: props.nodeItem?.nodeNo,
          modelNo: props.modelNo
        });
        await createNode(params);
      }
    } else {
      // 编辑接口
      await editNode(params);
    }
    createMessage.success(operationType.value === 'ADD' ? '新增成功！' : '编辑成功！');
    if (operationType.value !== 'ADD') {
      // 编辑
      if (originalSupplierName.value !== formState.supplierName) {
        // 强刷
        emits('strong-refresh', props.nodeNo);
      } else {
        // 编辑成功重新加载一次详情，去刷新列表的row
        // 通过接口返回
        const res = await getNodeDetail(formState.nodeNo);
        emits('refresh', props.nodeNo);
      }
    } else {
      // 新增
      let nodeNo = props.addType === 'peer' ? props.nodeItem?.parentNodeNo : props.nodeItem?.nodeNo;
      if (nodeNo === '-1') {
        emits('refresh-and-clear');
        emits('refresh');
      } else {
        emits('expand-refresh', nodeNo);
      }
      emits('load-bom-count');
    }
    dialogVisible.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  } finally {
    loading.value = false;
  }
}

/**
 * 切换物料类型时，做判断，如果是零部件，使用率则为100%
 */
watch(
  () => formState.dataType,
  type => {
    if (type === 'ITEM') {
      formState.useRate = 100;
      formState.recycleRate = 0;
      formState.deviationRange = 0;
    }
  }
);
</script>

<style lang="scss" scoped>
.material-input-has-append {
  :deep(.el-input-group__append) {
    position: absolute;
    padding: 0 12px;
    height: 30px;
    right: 0;
    background-color: transparent;
  }
  :deep(.el-input-group--append > .el-input__wrapper) {
    border-top-right-radius: 3px !important;
    border-bottom-right-radius: 3px !important;
  }
}
</style>
